package org.tru42.signal.processors.io;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.tru42.signal.lang.SObject;
import org.tru42.signal.lang.annotation.Sink;

public class FileWriter extends SObject {

	protected String filename;
	
	protected OutputStream outStream;

	@Sink
	public void input(long timestamp, byte value) {
		if(outStream == null) return;
		try {
			outStream.write(value);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Sink
	public void filename(long timestamp, String value) {
		filename = value;
		close();
		initFile();
	}
	
	@Override
	public void dispose() {
		super.dispose();
		close();
	}

	protected void close() {
		if(outStream != null)
			try { outStream.close(); } catch (IOException e) {}
	}
	
	protected void initFile() {
		close();
		try { outStream = new FileOutputStream(filename); } catch (IOException e) {}
	}
	
}
